package cn.edu.flink.tutorial.transform;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Reduce {
    public static void main(String[] args) throws Exception {
        // 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 从文件中读取数据
        String inputPath = "hello.txt";
        DataStreamSource<String> streamSource = env.readTextFile(inputPath);

        DataStream<Tuple2<String, Integer>> flatMapOutput = streamSource.flatMap(
                new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                        String[] strings = s.split(" ");
                        for (String string : strings) {
                            collector.collect(new Tuple2<>(string, 1));
                        }
                    }
                }
        );


        KeyedStream<Tuple2<String, Integer>, Tuple> keyedOutput = flatMapOutput.keyBy(0);

        DataStream<Tuple2<String, Integer>> reducedOutput = keyedOutput.reduce(
                new ReduceFunction<Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> reduce(Tuple2<String, Integer> stringIntegerTuple2, Tuple2<String, Integer> t1) throws Exception {
                        stringIntegerTuple2.f1 = stringIntegerTuple2.f1 + t1.f1;
                        return stringIntegerTuple2;
                    }
                }
        );

        reducedOutput.print();

        env.execute();
    }
}
